package com.example.myapplication;

import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;

public class MediaRecordActivity extends AppCompatActivity {

    private TextureView textureView;
    private Button beginButton;
    MediaRecorder mediaRecorder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_record);
        textureView = findViewById(R.id.textureView);
        beginButton = findViewById(R.id.btn_begin);
    }


    public void btnBegin(View view) {
        CharSequence text = beginButton.getText();
        Camera camera = Camera.open();
        //旋转相机
        camera.setDisplayOrientation(90);
        if (text.equals("开始录制")) {
            beginButton.setText("停止录制");
            camera.unlock();
            //初始化
            mediaRecorder = new MediaRecorder();
            //设置相机
            mediaRecorder.setCamera(camera);
            //设置源
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置音频源
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//设置视频源、
            //进入initialized状态，设置输出格式
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            //设置音视频编码格式
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
            //设置颠倒
            mediaRecorder.setOrientationHint(90);
            //设置输出文件
            mediaRecorder.setOutputFile(new File(getExternalFilesDir(""), "a.mp4").getAbsolutePath());
            //设置视频大小
            mediaRecorder.setVideoSize(640, 480);
            //设置显示区域
            mediaRecorder.setPreviewDisplay(new Surface(textureView.getSurfaceTexture()));
            try {
                mediaRecorder.prepare();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mediaRecorder.start();
        } else {
            beginButton.setText("开始录制");
            mediaRecorder.stop();
            mediaRecorder.release();
            camera.lock();
        }
    }

}